package com.ginage.gaugemanager.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import com.ginage.gaugemanager.mapper.entity.User;

/**
 * Servlet Filter implementation class LoginFilter
 */

@Component
public class LoginFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String requestURI = httpRequest.getRequestURI();

		// chain.doFilter(request, response);

		HttpSession session = httpRequest.getSession();
		User currentUser = (User) session.getAttribute("currentUser");
		if (currentUser == null) {
			if (requestURI.contains("/login.html") || 
					requestURI.contains("/js") || 
					requestURI.contains("/css")||
					requestURI.contains("/register")||
					requestURI.contains("checkEmployeeNum.do")||
					requestURI.contains("checkUsername.do")||
					requestURI.contains("afterRegister")||
					requestURI.contains("/images")||
					requestURI.contains("login.do")) {

				chain.doFilter(request, response);
				// return;
			}else {
				session.removeAttribute("error");
				httpResponse.sendRedirect("/gauge/login.html");
				
			}

		} else {
			chain.doFilter(request, response);
		}

	}

}
